import axios from "axios";
import { Axios } from "axios";

const serve = axios.create({
    baseURL: 'http://loclahost:8080/api',
    timeout: 5000,
    withCredentials: true
})

// 存储当前请求的取消函数，key可以是请求的url+参数或自定义id
const pendingRequests = new Map();

// 生成请求唯一key
function getRequestKey(config) {
    const { method, url, params, data } = config;
    return [method, url].join('&')
}

// 添加请求
function addPendingRequest(config) {
    const key = getRequestKey(config)
    if (pendingRequests.has(key)) {
        const controller = pendingRequests.get(key)
        controller.abort()
        pendingRequests.delete(key)
    } 
    const controller = new AbortController()
    config.signal = controller.signal
    pendingRequests.set(key, controller)
}

// 移除请求
function removePendingRequest(config) {
    const key = getRequestKey(config)
     pendingRequests.delete(key)
}

serve.interceptors.request.use(config => {
    addPendingRequest(config)
    return config
}, err => {
    Promise.reject(err)
})

serve.interceptors.response.use(response => {
    removePendingRequest(response.config);
    return response
}, error => {
    if (axios.isCancel(error)) {
        console.log('请求取消', error.message);
    }
    if (error.config) {
        removePendingRequest(error.config);
    }
    return  Promise.reject(error)
})

export default serve;